package com.medicine.hbp.uitl;

import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;


/**
 * 加密工具类
 * @author chi.wang
 * @time 2016-09-03
 */
public class EncryUtils {

	/**
	 * MD5加密
	 * @param str
	 * @return
	 */
	public static String getMD5String(String str) {
		try{
			byte[] res=str.getBytes();
			MessageDigest md = MessageDigest.getInstance("MD5".toUpperCase());
			byte[] hash=md.digest(res);
//            for(int i=0;i<result.length;i++){
//                md.update(result[i]);
//            }
//            byte[] hash=md.digest();
			StringBuffer d=new StringBuffer("");
			for(int i=0;i<hash.length;i++){
				int v=hash[i] & 0xFF;
				if(v<16) d.append("0");
				d.append(Integer.toString(v,16).toUpperCase()+"");
			}
			return d.toString();
		}catch(Exception e){
			return "";
		}
	}

	/**
	 * MD5加密
	 * @param data
	 * @return
	 * @throws IOException
	 */
	public static String byte2hex(String data) throws IOException {
		byte[] bytes = getMD5Digest(data);
		StringBuilder sign = new StringBuilder();
		for (int i = 0; i < bytes.length; i++) {
			String hex = Integer.toHexString(bytes[i] & 0xff);
			if (hex.length() == 1) {
				sign.append("0");
			}
			sign.append(hex.toUpperCase());
		}
		return sign.toString();
	}

	/**
	 * 将str 进行md5加密
	 * @param data
	 * @return
	 * @throws IOException
	 */
	private static byte[] getMD5Digest(String data) throws IOException {
		byte[] bytes = null;
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			bytes = md.digest(data.getBytes("UTF-8"));
		} catch (GeneralSecurityException gse) {
			throw new IOException(gse);
		}
		return bytes;
	}

}
